package com.fileshare.web.service.impl;

import com.fileshare.web.dao.FileResourceRepository;
import com.fileshare.web.dto.Bo.UploadFileBo;
import com.fileshare.web.dto.Vo.FileResourceVo;
import com.fileshare.web.entity.Article;
import com.fileshare.web.entity.FileResource;
import com.fileshare.web.entity.User;
import com.fileshare.web.service.DownloadService;
import com.fileshare.web.service.FileResourceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class FileResourceServiceImpl implements FileResourceService {

    @Resource
    private FileResourceRepository resourceRepository;
    @Resource
    private DownloadService downloadService;

    @Override
    @Transactional
    public FileResource addResource(UploadFileBo fileBo, String resourceUrl, User user) {
        FileResource resource = new FileResource();
        String userSeq = user.getUserSeq();
        Date now = new Date();
        resource.setCreateAt(now);
        resource.setUpdateAt(now);
        resource.setCreateBy(userSeq);
        resource.setUpdateBy(userSeq);
        resource.setFileSeq(resourceRepository.generateSeq());
        resource.setDescription("");
        resource.setFileLocation(resourceUrl);
        resource.setName(fileBo.getFilename());
        resourceRepository.save(resource);
        return resource;
    }

    @Override
    public boolean bindFileToArticle(Article article, List<String> fileSeqs) {
        for (String fileSeq : fileSeqs) {
            try {
                FileResource resource = resourceRepository.findBySeq(fileSeq);
                if (resource != null) {
                    resource.setReferenceSeq(article.getArticleSeq());
                    resourceRepository.update(resource);
                }
            } catch (Exception exception) {
                return false;
            }
        }
        return true;
    }

    @Override
    public List<FileResourceVo> getArticleResources(String articleSeq) {
        List<FileResource> resources = resourceRepository.findByArticleSeq(articleSeq);
        downloadService.saveLog(resources);
        return FileResourceVo.fromEntities(resources);
    }

}
